package saas.baseinfo.service.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * @author guan.xin
 * @title MessageUtils
 * @description
 * @create 2022-05-24 15:41
 * @since JDK8
 */
@Component
public class MessageUtils implements ApplicationContextAware {

    private static MessageSource messageSource;

    /**
     * 获取指定key的指定语言的翻译值
     */
    public static String get(String msgKey, String lang) {
        try {
            return messageSource.getMessage(msgKey, null, new Locale(lang));
        } catch (Exception e) {
            return msgKey;
        }
    }

    /**
     * 获取指定key的国际化翻译值
     */
    public static String get(String msgKey) {
        try {
            return messageSource.getMessage(msgKey, null, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return msgKey;
        }
    }

    /**
     * 获取指定key的国际化翻译值，翻译值带占位符参数
     */
    public static String get(String msgKey, Object... args) {
        try {
            return messageSource.getMessage(msgKey, args, LocaleContextHolder.getLocale());
        } catch (Exception e) {
            return msgKey;
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (null == messageSource) {
            messageSource = applicationContext.getBean(MessageSource.class);
        }
    }
}
